##=============================================================================
## Appendix: Table 5
##=============================================================================

##-----------------
# clear environment
rm(list=ls())
options(stringsAsFactors = FALSE, scipen = 999)
# source("R/functions.R")

##--------
# Set seed
seed <- sample.int(.Machine$integer.max, 1)
set.seed(seed)

##-------------
# Load Packages
ipak <- function(pkg){new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if(length(new.pkg)) install.packages(new.pkg, dependencies = TRUE)
sapply(pkg, require, character.only = TRUE)
}

packages <- c("tidyverse", "lme4", "sjPlot", "ordinal", "texreg", "hrbrthemes")


ipak(packages)

##---------
# Load Data
#setwd("~/Dropbox/Ukraine2022WartimeSurvey/Paper_peace/final_version_oct_2024/replication-scripts")
load("clean_ukraine_data.RData")

# Random Effects at the District Level
fit <- lmer(save_lives_z ~ 1 + wave + survival_mindset + per_idx_invcov + 
               fam_idx_invcov + frontline_b + displaced + sex + rus_ethnic +
               age + edu + job + ln_viina_two_months + finances +
               (1 + wave + survival_mindset + per_idx_invcov + fam_idx_invcov | 
                  adm2_en), data = dat)

# Warning: singular fit, bad specification (perhaps better at ADM1 level)

sjPlot::tab_model(fit)
#sjPlot::plot_model(fit)

#----------------------
# Export models to LaTeX
coef_names <- c("(Intercept)",
                "Survey Wave",
                "Survival Mindset",
                "Personal Victimization",
                "Family Victimization",
                "Frontline Oblast",
                "Displaced",
                "Sex",
                "Ethnic Russian",
                "Age",
                "Education",
                "Employment",
                "Ln(VIINA)",
                "Socio-Economic Status")

mod_names <- "Save Lives (z-std)"

note <- "This is a footnote."

#screenreg(list(fit1, fit2, fit3, fit4, fit5))

texreg(fit, 
       dcolumn = TRUE,
       omit.coef = "\\(Intercept\\)",
       custom.coef.names = coef_names,
       custom.model.names = mod_names,
       custom.note = str_c("Note: ", note),
       caption.above = TRUE,
       #caption = "Caption",
       digits = 3, 
       leading.zero = TRUE,
       fontsize = "small")

rm(list = ls())
##=============================================================================
## End of File
##=============================================================================